package com.hundun.hddeal.util;

import com.google.gson.Gson;
import com.hundun.hddeal.entity.QinIuBean;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

@Slf4j
public class QiniuUtil {

    public static String QINNIU_URL = "http://hundun.icaoguo.com/";
    //设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "9T-eM5IHaQKhWonwCYro0Jx9NpyFjeyAdyoV9sCm";
    private static final String SECRET_KEY = "w-2I-PMFq9EIE2A7U0U1Mt-yPTo8tIDsv6kfJiYU";

    //要上传的空间
    private static final String bucketname = "hundun4a";

    //密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    //普通上传
    public QinIuBean upload(BufferedImage bufferedImage, String fileName) {
        //创建上传对象
        byte[] uploadByte = imageToBytes(bufferedImage, "jpg");
        return upload(uploadByte, fileName);
    }

    //普通上传
    public QinIuBean upload(BufferedImage bufferedImage, String fileName, String format) {
        //创建上传对象
        byte[] uploadByte = imageToBytes(bufferedImage, format);
        return upload(uploadByte, fileName);
    }

    //普通上传

    /**
     * 普通上传
     *
     * @param filePath
     * @param fileName
     * @throws IOException
     */
    public QinIuBean upload(Object filePath, String fileName) {
        /**构造一个带指定Zone对象的配置类
         *华东	Zone.zone0()
         *华北	Zone.zone1()
         * 华南	Zone.zone2()
         * 北美	Zone.zoneNa0()
         */
        Configuration cfg = new Configuration(Zone.zone0());
        //创建上传对象  
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            //调用put方法上传
            Response res;
            if (filePath instanceof byte[]) {
                res = uploadManager.put((byte[]) filePath, fileName, auth.uploadToken(bucketname));
                log.info("七牛上传:{}", res.bodyString());
                return new Gson().fromJson(res.bodyString(), QinIuBean.class);
            }
            if (filePath instanceof File) {
                res = uploadManager.put((File) filePath, fileName, auth.uploadToken(bucketname));
                log.info("七牛上传:{}", res.bodyString());
                return new Gson().fromJson(res.bodyString(), QinIuBean.class);
            }

            if (filePath instanceof String) {
                res = uploadManager.put((String) filePath, fileName, auth.uploadToken(bucketname));
                log.info("七牛上传:{}", res.bodyString());
                return new Gson().fromJson(res.bodyString(), QinIuBean.class);
            }
            log.info("七牛上传:{}", "参数不对");
            return null;
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            try {
                log.info("七牛上传失败:{}", r.bodyString());
                return null;
                //响应的文本信息
            } catch (QiniuException e1) {
                return null;
                //ignore
            }
        }
    }

    //普通删除
    public void delete(String key) {
        if (TextUtils.isEmpty(key))
            return;
        //实例化一个BucketManager对象
        Configuration cfg = new Configuration(Zone.zone0());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //此处的33是去掉：http://ongsua0j7.bkt.clouddn.com/,剩下的key就是图片在七牛云的名称
        key = key.substring(QiniuUtil.QINNIU_URL.length(), key.length());
        try {
            //调用delete方法移动文件
            Response r = bucketManager.delete(bucketname, key);
            log.info("七牛删除:{}", r.bodyString());
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    /**
     * 转换BufferedImage 数据为byte数组
     * <p>
     * Image对象
     *
     * @param format image格式字符串.如"gif","png"
     * @return byte数组
     */
    private byte[] imageToBytes(BufferedImage bImage, String format) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, format, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
}